package cn.stimd.spring.format.number;

import cn.stimd.spring.format.Formatter;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Currency;
import java.util.Locale;

/**
 * Created by Stimd
 * 项目地址：https://gitee.com/stimd/spring-wheel
 * 公众号：Java编程探微
 */
public class CurrencyStyleFormatter implements Formatter<Number> {
    //小数位数
    private int fractionDigits = 2;
    //近似值模式
    private RoundingMode roundingMode;
    //货币
    private Currency currency;
    //指定格式
    private String pattern;


    @Override
    public Number parse(String text, Locale locale) throws ParseException {
        BigDecimal decimal = (BigDecimal) getNumberFormat(locale).parse(text);
        if (decimal != null) {
            if (this.roundingMode != null) {
                decimal = decimal.setScale(this.fractionDigits, this.roundingMode);
            }
            else {
                decimal = decimal.setScale(this.fractionDigits);
            }
        }
        return decimal;
    }


    @Override
    public String print(Number number, Locale locale) {
        return getNumberFormat(locale).format(number);
    }


    protected NumberFormat getNumberFormat(Locale locale) {
        DecimalFormat format = (DecimalFormat) NumberFormat.getCurrencyInstance(locale);
        format.setParseBigDecimal(true);
        format.setMaximumFractionDigits(this.fractionDigits);
        format.setMinimumFractionDigits(this.fractionDigits);
        if (this.roundingMode != null) {
            format.setRoundingMode(this.roundingMode);
        }
        if (this.currency != null) {
            format.setCurrency(this.currency);
        }
        if (this.pattern != null) {
            format.applyPattern(this.pattern);
        }
        return format;
    }


    public void setFractionDigits(int fractionDigits) {
        this.fractionDigits = fractionDigits;
    }
    public void setRoundingMode(RoundingMode roundingMode) {
        this.roundingMode = roundingMode;
    }
    public void setCurrency(Currency currency) {
        this.currency = currency;
    }
    public void setPattern(String pattern) {
        this.pattern = pattern;
    }
}
